import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { Link } from 'react-router-dom';
import './index.css';
import { Tag, Spin } from 'antd';

const tabType = new Map([
  ['share', '分享'],
  ['ask', '问答'],
  ['job', '招聘'],
]);

const Collect: React.FunctionComponent = () => {
  const username = localStorage.getItem('loginname') || '';

  const [topicList, setTopicList] = useState<ITopic[]>([]);

  useEffect(() => {
    getCollect();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const getCollect = async () => {
    if (username === '') {
      return;
    }
    const response = await fetch(
      `https://cnodejs.org/api/v1/topic_collect/${username}`
    );
    const { data } = await response.json();

    setTopicList(data);
  };

  return (
    <div className="collect">
      <span className="collect-title">
        <Link to={`/user/${username}`}>{username}</Link>收藏的帖子
      </span>
      <div className="collect-content">
        {username === '' ? (
          <p className="unlogin">请登录!</p>
        ) : topicList.length > 0 ? (
          <ul>
            {topicList.map((item, index) => {
              return (
                <li key={item.id}>
                  <span>
                    <Link to={`/user/${item.author.loginname}`}>
                      <img
                        src={item.author.avatar_url}
                        alt={item.author.loginname}
                      />
                    </Link>
                    {item.top ? (
                      <Tag color="green">置顶</Tag>
                    ) : item.good ? (
                      <Tag color="green">精华</Tag>
                    ) : (
                      <Tag>{tabType.get(item.tab) as string}</Tag>
                    )}
                    <Link to={`/topic/${item.id}`}>{item.title}</Link>
                  </span>
                  <span>{moment(item.last_reply_at).format('YYYY-MM-DD')}</span>
                </li>
              );
            })}
          </ul>
        ) : (
          <Spin className="loading" />
        )}
      </div>
    </div>
  );
};

export default Collect;
